/**
 * memca.c
 * 单条独立内存分配管理实现
 * 
 * 竹影半墙
 * 2023.08
 */
#include "bsw_memca.h"

static bsw_always_inline uint16_t mca_size_real(bsw_memca_s *ma)
{
    return bsw_max(ma->size, sizeof(void*));
}

#if 0
#endif
void bsw_mca_init(bsw_memca_s *ma)
{
    void *last;
    uint32_t max;
    uint16_t size = mca_size_real(ma);

    max  = ma->max;
    last = NULL;

    ma->head = NULL;
    ma->size = size;
    ma->num = 0;
    while (max--) {
        void *v = malloc(size);
        if (!v)
            return ;
        if (!last) {
            ma->head = last = v;
        } else {
            *(void **) last = v;
            last = v;
        }
        *(void **)v = NULL;
        ma->num += 1;
    }
    return ;
}

void bsw_mca_close(bsw_memca_s *ma)
{
    void *v;

    while ((v=ma->head)) {
        ma->head = *(void **)v;
        ma->num -= 1;
        free(v);
    }
    return ;
}

void * bsw_mca_alloc(bsw_memca_s *ma)
{
    void *v;

    v = bsw_ma_alloc(ma, &ma->head, 1);
    return v ?: malloc(ma->size);
}

void bsw_mca_free(bsw_memca_s *ma, void *v)
{
    bsw_ma_free(ma, &ma->head, v, 0);
    return ;
}